#  cmod - set up the user environment with module files.
#  Copyright (C) 1998 by the authors of cmod (see AUTHORS).
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */

import string
import sys
import os
import fnmatch

PATTERNS = [
    ("*", ".sh", "simplesh"),
    ("*", ".ok", "simpleok"),
    ("*", ".sh.in", "genshsrc"),
    ("*", ".ok.in", "genoksrc"),
    ("t[0-9][0-9][0-9]-[0-9]", "", "modules"),
    ]

error_found = 0

def pretty_fmt(l):
    lst = l
    lst.sort()
    return string.joinfields(lst, " ")

class target:
    def __init__(self, base):
	self.__base = base
	self.__deps = {}
	self.__target = None

    def add_dep(self, key, file):
	global error_found

	if self.__deps.has_key(key):
	    sys.stderr.write("More than one %s for %s: %s, %s\n" %
			     (key, self.__base, self.__deps[key], file))
	    error_found = 1
	self.__deps[key] = file

    def a_or_b(self, a, b):
	global error_found

	if self.__deps.has_key(a) and not self.__deps.has_key(b):
	    return 1
	elif self.__deps.has_key(b) and not self.__deps.has_key(a):
	    return 0
	elif self.__deps.has_key(a) and self.__deps.has_key(b):
	    sys.stderr.write("%s depends on both %s and %s\n" %
			     (self.__base, self.__deps[a], self.__deps[b]))
	else:
	    sys.stderr.write("%s depends on neither %s nor %s\n" %
			     (self.__base, a, b))
	error_found = 1
	return -1

    def compute(self):
	if self.__target != None:
	    return

	sh_style = self.a_or_b("simplesh", "genshsrc")
	ok_style = self.a_or_b("simpleok", "genoksrc")
	if sh_style < 0 or ok_style < 0:
	    return

	self.__immediate_deps = []
	self.__derived_deps = []
	if sh_style:
	    self.__immediate_deps.append(self.__deps["simplesh"])
	else:
	    sh_base = self.__deps["genshsrc"][:-3]
	    self.__immediate_deps.append(sh_base + ".gen")
	    self.__derived_deps.append(sh_base + ".gen: " + sh_base + ".in\n")

	if ok_style:
	    self.__immediate_deps.append(self.__deps["simpleok"])
	else:
	    ok_base = self.__deps["genoksrc"][:-3]
	    self.__immediate_deps.append(ok_base + ".gen")
	    self.__derived_deps.append(ok_base + ".gen: " + ok_base + ".in\n")

	self.__key = "gs"[sh_style] + "gs"[ok_style]
	self.__target = self.__base + ".out" + self.__key

    def category(self):
	self.compute()
	return self.__key

    def target(self):
	self.compute()
	return self.__target

    def dep_line(self):
	return (self.target() + ": "
		+ string.joinfields(self.__immediate_deps, " ")
		+ "\n" + string.joinfields(self.__derived_deps, ""))

def doit():
    if len(sys.argv) != 3:
	sys.stderr.write("usage: python gen-makefile.py infile outfile\n")
	sys.exit(1)

    infile = open(sys.argv[1], "r")
    tmpl = infile.read()
    infile.close()

    globbed = {}
    out = {}
    for (pattern, suffix, key) in PATTERNS:
	globbed[key] = []
    
    for file in os.listdir("."):
	for (pattern, suffix, key) in PATTERNS:
	    if fnmatch.fnmatch(file, pattern + suffix):
		globbed[key].append(file)
		if suffix != "":
		    base = file[:-len(suffix)]
		    if not out.has_key(base):
			out[base] = target(base)
		    out[base].add_dep(key, file)

    subst = {}
    for (pattern, suffix, key) in PATTERNS:
	subst[key] = pretty_fmt(globbed[key])

    subst["genok"] = pretty_fmt(map(lambda x: x[:-3] + ".gen",
				    globbed["genoksrc"]))
    subst["gensh"] = pretty_fmt(map(lambda x: x[:-3] + ".gen",
				    globbed["genshsrc"]))

    dep_lines = []
    out_categories = {"ss":[],
		      "sg":[],
		      "gs":[],
		      "gg":[]}
    for k in out.keys():
	dep_lines.append(out[k].dep_line())
	out_categories[out[k].category()].append(out[k].target())

    for cat in out_categories.keys():
	subst["out" + cat] = pretty_fmt(out_categories[cat])
    subst["dep_lines"] = string.joinfields(dep_lines, "")

    outfile = open(sys.argv[2] + ".tmp", "w")
    outfile.write(
	"# This file was generated by gen-makefile.py.  Do not edit.\n\n" +
	(tmpl % subst))
    outfile.close()
    os.rename(sys.argv[2] + ".tmp", sys.argv[2])

doit()
sys.exit(0)
